package codeMaker.impl;

import codeMaker.CallGood;
import codeMaker.CommonParamsConfig;
import codeMaker.DataBaseConfig;
import codeMaker.LoginConfig;
import codeMaker.MakeCode;
import codeMaker.MakeEntity;
import codeMaker.MutiTableConfig;
import codeMaker.TablesQuery;
import codeMaker.UtilDownLoad;
import constant.ChildWindowConstant;
import constant.CodeConstant;
import constant.Constant;
import entity.DataSourceModel;
import entity.DatabaseModel;
import entity.Parameters;
import main.MainMethod;
import util.CodeWriterUtil;
import util.ConfigUtil;
import util.DBUtils;

import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CodeListener
 * @Author zrx
 * @Date 2021/11/23 12:46
 */
public class MakeCodeImpl extends MakeCode {

	private static volatile MakeCodeImpl makeCodeListener;

	public static MakeCodeImpl getInstance() {
		if (null == makeCodeListener) {
			synchronized (MakeCodeImpl.class) {
				if (null == makeCodeListener) {
					makeCodeListener = new MakeCodeImpl();
				}
			}
		}
		return makeCodeListener;
	}

	private MakeCodeImpl() {
	}

	/**
	 * 生成代码的listener
	 *
	 * @param loginConfig
	 * @param btnNewButton
	 * @param clientStyle
	 * @param tips
	 * @param jsFrameWorkComBox
	 * @param themeComboBox
	 * @param authorityCheckBox
	 */
	public void setMakeCodeListener(JComboBox<String> loginConfig, JButton btnNewButton, JComboBox<String> clientStyle, JLabel tips, JComboBox<String> jsFrameWorkComBox, JComboBox<String> themeComboBox, JCheckBox authorityCheckBox) {
		btnNewButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				// 按钮不可用
				btnNewButton.setEnabled(false);
				tips.setText("检查配置 and 代码生成中，请耐心等待。。。");
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				try {
					String projectNameVal = projectName.getText();
					projectNameVal = CodeWriterUtil.spStrFilter(projectNameVal);
					if ("".equals(projectNameVal)) {
						projectNameVal = Constant.PROJECT_NAME;
					}
					String frameWorkVal = (String) framework.getSelectedItem();
					String dataBaseTypeVal = (String) databaseType.getSelectedItem();
					String clientFrameWorkVal = (String) clientStyle.getSelectedItem();
					String jsFrameWork = (String) jsFrameWorkComBox.getSelectedItem();
					String themeVal = (String) themeComboBox.getSelectedItem();
					boolean isAuthority = authorityCheckBox.isSelected();
					Parameters parameters = checkNeccessary();
					if (parameters == null) {
						JOptionPane.showMessageDialog(frmv, "带红色星号的为必填项目，请选择一个数据源作为主数据源，选择多数据源模式可生成多数据源版本代码，不选则生成常规单数据源代码！", "警告", JOptionPane.ERROR_MESSAGE);
						return;
					}
					String loginValue = (String) loginConfig.getSelectedItem();

					//如果选择开启了多数据源模式
					if (isMutiDataSource.isSelected()) {
						//遍历所有数据源检验
						for (Map.Entry<String, DataSourceModel> entry : ChildWindowConstant.dataSourceModelMap.entrySet()) {
							String dataSourceName = entry.getKey();
							DataSourceModel dataSourceModel = entry.getValue();
							Parameters param = new Parameters();
							param.setDataSourceName(dataSourceName);
							param.setDataBaseTypeVal(dataSourceModel.getDataBaseTypeVal());
							param.setDataBaseIpVal(dataSourceModel.getDataBaseIpVal());
							param.setDataBasePortVal(dataSourceModel.getDataBasePortVal());
							param.setDataBaseNameVal(dataSourceModel.getDataBaseNameVal());
							param.setDataBaseUserNameVal(dataSourceModel.getDataBaseUserNameVal());
							param.setDataBasePwdVal(dataSourceModel.getDataBasePwdVal());
							param.setTableName(dataSourceModel.getTableName());
							//检查数据库连接配置
							if (isNotPassDataBaseConfig(param, dataSourceModel.getPrimaryKeyListMap(), dataSourceModel.getAllColumnMsgMap(), dataSourceModel.getColumnMsgMap())) {
								return;
							}
							//设置数据库连接信息
							dataSourceModel.setDataBaseDriverClass(param.getDataBaseDriverClass());
							dataSourceModel.setDataBaseUrl(param.getDataBaseUrl());
							//设置parameters的连接信息
							if (dataSourceName.equals(parameters.getDataSourceName())) {
								parameters.setDataBaseDriverClass(param.getDataBaseDriverClass());
								parameters.setDataBaseUrl(param.getDataBaseUrl());
							}
						}
					} else {
						if (isNotPassDataBaseConfig(parameters, ChildWindowConstant.primaryKeyListMap, ChildWindowConstant.allColumnMsgMap, ChildWindowConstant.columnMsgMap)) {
							return;
						}
					}

					//自定义生成功能模块
					customBuild(parameters);

					if (!parameters.isController() && !parameters.isService() && !parameters.isDao() && !parameters.isEntity() && !parameters.isView()) {
						//如果添加了权限管理，给予提示
						if (isAuthority) {
							JOptionPane.showMessageDialog(frmv,
									"检测到您选择添加了权限管理模块，将在生成代码时自动在《主数据源的数据库》中为您创建相关的表：" + CodeConstant.NEW_LINE + CodeConstant.NEW_LINE
											+ " cm_sys_user 用户表" + CodeConstant.NEW_LINE + CodeConstant.NEW_LINE
											+ " cm_sys_role 角色表" + CodeConstant.NEW_LINE + CodeConstant.NEW_LINE
											+ " cm_sys_menu 菜单表" + CodeConstant.NEW_LINE + CodeConstant.NEW_LINE
											+ " cm_sys_role_menu 菜单角色关联表" + CodeConstant.NEW_LINE + CodeConstant.NEW_LINE
											+ " cm_sys_button 按钮表" + CodeConstant.NEW_LINE + CodeConstant.NEW_LINE
											+ " cm_sys_role_button 角色按钮关联表" + CodeConstant.NEW_LINE + CodeConstant.NEW_LINE
											+ " 并且在前台添加角色和菜单管理模块实现按钮级别的权限控制！" + CodeConstant.NEW_LINE + CodeConstant.NEW_LINE
											+ " 注意：选择此项登录配置会失效！请确保当前数据库用户有建表权限，否则该功能无法使用！！",
									"提示", JOptionPane.INFORMATION_MESSAGE);
						} else {
							// 判断并处理登录用户相关
							if (!dealDymaicAndStaticUser(loginValue)) {
								return;
							}
						}
					}

					int getCodeConfirmDialog = JOptionPane.showConfirmDialog(frmv,
							"当前项目名称为：" + projectNameVal + CodeConstant.NEW_LINE
									+ "当前前台风格选择为：" + clientFrameWorkVal + CodeConstant.NEW_LINE
									+ "js框架选择为：" + jsFrameWork + CodeConstant.NEW_LINE
									+ "后台框架选择为：" + frameWorkVal + CodeConstant.NEW_LINE
									+ "确认生成吗？？",
							"提示", JOptionPane.YES_NO_OPTION);
					if (getCodeConfirmDialog != 0) {
						return;
					}
					// 最后设置共性信息
					parameters.setProjectNameVal(projectNameVal);
					parameters.setFrameWorkVal(frameWorkVal);
					parameters.setClientFrameWorkVal(clientFrameWorkVal);
					parameters.setMakeModelVal(loginValue);
					parameters.setJsFrameWork(jsFrameWork);
					parameters.setThemeVal(themeVal);
					parameters.setAuthority(isAuthority);

					//保存当前配置配置，下次直接用
					ConfigUtil.saveConfig(parameters);
					// System.out.println(parameters);
					boolean progressFlg = MainMethod.progress(parameters);

					if (progressFlg) {
						tips.setText("           代码生成完毕！");
						String msg = "";
						if (parameters.isController() || parameters.isService() || parameters.isDao() || parameters.isEntity() || parameters.isView()) {
							msg = "您选择的模块已生成完毕，是否打开生产目录？";
						} else if (CodeConstant.OLD_THEME.equals(themeVal)) {
							msg = "代码生成完毕，编码为utf-8，导入eclipse/idea运行，访问 http://localhost:8080/" + projectNameVal + "/login 即可！"
									+ CodeConstant.NEW_LINE + "如没有进行数据库登录的配置 ,默认用户名为admin，密码为" + (isAuthority ? "123456" : "root")
									+ CodeConstant.NEW_LINE + "是否打开生产目录？";
						} else if (CodeConstant.H_ADMIN_THEME.equals(themeVal)) {
							msg = "代码生成完毕，编码为utf-8" + CodeConstant.NEW_LINE
									+ "后台项目导入eclipse/idea运行，访问http://localhost:8080/" + projectNameVal + "/views/login.html即可！"
									+ CodeConstant.NEW_LINE + "如没有进行数据库登录的配置 ,默认用户名为admin，密码为" + (isAuthority ? "123456" : "root")
									+ CodeConstant.NEW_LINE + "是否打开生产目录？";
						}
						int showConfirmDialog = JOptionPane.showConfirmDialog(frmv, msg, "提示",
								JOptionPane.YES_NO_OPTION);
						if (showConfirmDialog == 0) {
							Desktop.getDesktop().open(new File(parameters.getOutPathVal()));
						}
						return;
					}
					JOptionPane.showMessageDialog(frmv, "代码生成过程中出现错误，请仔细检查再次生成！", "错误", JOptionPane.ERROR_MESSAGE);
				} catch (Exception ex) {
					JOptionPane.showMessageDialog(frmv, "出现未知错误！", "错误", JOptionPane.ERROR_MESSAGE);
				} finally {
					tips.setText("");
					// 按钮可用
					btnNewButton.setEnabled(true);
				}
			}
		});
	}

	/**
	 * 自定义生成功能模块
	 *
	 * @param parameters
	 */
	private void customBuild(Parameters parameters) {
		boolean isController = controllerBox.isSelected();
		boolean isService = serviceBox.isSelected();
		boolean isDao = daoBox.isSelected();
		boolean isEntity = entityBox.isSelected();
		boolean isView = viewBox.isSelected();
		//如果选择了自定义生成模块，给予提示
		if (isController || isService || isDao || isEntity || isView) {
			JOptionPane.showMessageDialog(frmv, "检测到您自己选择了生成模块，选择后只会生成指定模块的代码，不选则生成完整项目，适用于已经用代码生成器生成完项目还想追加功能模块的场景！"
							+ CodeConstant.NEW_LINE + "注意：如果要生成的模块在项目中已存在并且您已经做了部分修改，生成后会被覆盖，建议换一个文件夹生成然后复制过去，如果是全新模块，直接在项目路径生成即可！",
					"提示", JOptionPane.INFORMATION_MESSAGE);
		}
		parameters.setController(isController);
		parameters.setService(isService);
		parameters.setDao(isDao);
		parameters.setEntity(isEntity);
		parameters.setView(isView);
	}


	/**
	 * 添加权限 listener
	 *
	 * @param loginConfig
	 * @param authorityCheckBox
	 */
	public void setAuthListener(JComboBox<String> loginConfig, JCheckBox authorityCheckBox) {
		authorityCheckBox.addActionListener(e -> {
			if (authorityCheckBox.isSelected()) {
				loginConfig.setEnabled(false);
			} else {
				loginConfig.setEnabled(true);
			}
		});
	}

	/**
	 * 数据库配置的listener
	 *
	 * @param tips
	 * @param databaseConfig
	 */
	public void setDataBaseConfigListener(JLabel tips, JButton databaseConfig) {
		databaseConfig.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				databaseConfig.setEnabled(false);
				tips.setText("当前正在检查数据库配置中，请耐心等待。。。");
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				try {
					Parameters parameters = checkNeccessary();
					if (parameters == null) {
						JOptionPane.showMessageDialog(frmv, "带红色星号的为必填项目！请选择一个数据源作为主数据源，然后使用数据库配置！", "警告",
								JOptionPane.ERROR_MESSAGE);
						return;
					}
					Connection connection = DBUtils.getConnection(parameters);
					if (connection == null) {
						return;
					} else {
						connection.close();
					}
					if ("".equals(tableName.getText())) {
						JOptionPane.showMessageDialog(Constant.frmv, "请先填写数据表的名称再进行配置！", "错误",
								JOptionPane.ERROR_MESSAGE);
						return;
					}
					StringBuilder tipStr = new StringBuilder();
					String[] tableNameArr = tableName.getText().split("#");
					String databaseTypeVal = (String) databaseType.getSelectedItem();
					for (int i = 0; i < tableNameArr.length; i++) {
						List<String> columnNameList = DBUtils.getColumnNameList(databaseTypeVal, tableNameArr[i],
								DBUtils.getConnection(parameters));
						if (columnNameList != null) {
							continue;
						}
						if (i == tableNameArr.length - 1) {
							tipStr.append(tableNameArr[i]);
							break;
						}
						tipStr.append(tableNameArr[i]).append(",");
					}
					// 如果提示不为空，说明有表名填写出现问题
					if (!"".equals(tipStr.toString())) {
						JOptionPane.showMessageDialog(frmv,
								"查询数据表 " + tipStr
										+ " 时出现未知错误！请仔细检查表名是否配置正确（postgresql需要模式名.表名（除public模式））！表名与表名之前是否使用#隔开！",
								"错误", JOptionPane.ERROR_MESSAGE);
						return;
					}
					if (ChildWindowConstant.dataBaseConfig == null) {
						DataBaseConfig.main(parameters);
						return;
					}
					ChildWindowConstant.dataBaseConfig.dispose();
					ChildWindowConstant.dataBaseConfig = null;
					DataBaseConfig.main(parameters);
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(frmv,
							"数据库配置时出错：" + e1.getMessage(),
							"错误", JOptionPane.ERROR_MESSAGE);
				} finally {
					tips.setText("");
					databaseConfig.setEnabled(true);
				}
			}
		});
	}


	/**
	 * 选择文件的listener
	 *
	 * @param button
	 */
	public void setPathChooseListener(JButton button) {
		button.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				JFileChooser jfc = new JFileChooser();
				jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int flg = jfc.showDialog(new JLabel(), "选择");
				// 如果选择了文件
				if (flg == JFileChooser.APPROVE_OPTION) {
					File file = jfc.getSelectedFile();
					outPath.setText(file.getAbsolutePath());
				}
			}
		});
	}

	/**
	 * 登录配置listener
	 *
	 * @param loginConfig
	 */
	public void setLoginConfigListener(JComboBox<String> loginConfig) {
		loginConfig.addActionListener(e -> {
			String loginItem = (String) loginConfig.getSelectedItem();
			dealDymaicAndStaticUser(loginItem);
		});
	}

	/**
	 * 多表联查的listener
	 *
	 * @param tablesQuery
	 */
	public void setTablesQueryListener(JMenuItem tablesQuery) {
		tablesQuery.addActionListener(e -> {
			Parameters parameters = checkNeccessary();
			if (parameters == null) {
				JOptionPane.showMessageDialog(frmv, "带红色星号的为必填项目！请选择一个数据源作为主数据源，然后再使用多表联查配置！", "警告", JOptionPane.ERROR_MESSAGE);
				return;
			}
			Connection connection = DBUtils.getConnection(parameters);
			if (connection == null) {
				int ifGo = JOptionPane.showConfirmDialog(frmv, "数据库连接失败，请检查配置信息，生成后程序会无法运行,确定继续配置吗？", "提示",
						JOptionPane.YES_NO_OPTION);
				if (ifGo != 0) {
					return;
				}
			} else {
				try {
					connection.close();
				} catch (SQLException ignored) {
				}
			}
			if (ChildWindowConstant.tablesQuery == null) {
				TablesQuery.main(parameters);
				return;
			}
			ChildWindowConstant.tablesQuery.getFrame().dispose();
			ChildWindowConstant.tablesQuery = null;
			TablesQuery.main(parameters);
		});
	}

	/**
	 * 登录功能定制的 listener
	 *
	 * @param loginItem
	 */
	public void setLoginListener(JMenuItem loginItem) {
		loginItem.addActionListener(e -> {
			if (ChildWindowConstant.loginConfig == null) {
				LoginConfig.main();
				return;
			}
			ChildWindowConstant.loginConfig.getFrame().dispose();
			ChildWindowConstant.loginConfig = null;
			LoginConfig.main();
		});
	}

	/**
	 * 自定义实体的 listener
	 *
	 * @param makeEntity
	 */
	public void setMakeEntityListener(JMenuItem makeEntity) {
		makeEntity.addActionListener(e -> {
			if (ChildWindowConstant.makeEntity == null) {
				MakeEntity.main();
				return;
			}
			ChildWindowConstant.makeEntity.getFrame().dispose();
			ChildWindowConstant.makeEntity = null;
			MakeEntity.main();
		});
	}

	/**
	 * 常用功能listener
	 *
	 * @param usualModel
	 */
	public void setUsualListener(JMenuItem usualModel) {
		usualModel.addActionListener(e -> JOptionPane.showMessageDialog(frmv, "功能正在开发当中。。。！", "提示", JOptionPane.ERROR_MESSAGE));
	}

	/**
	 * 常用参数配置 listener
	 *
	 * @param commonParamsMenu
	 */
	public void setCommonParamListener(JMenuItem commonParamsMenu) {
		commonParamsMenu.addActionListener(e -> {
			if (ChildWindowConstant.commonParamsConfig == null) {
				CommonParamsConfig.main();
				return;
			}
			ChildWindowConstant.commonParamsConfig.getFrame().dispose();
			ChildWindowConstant.commonParamsConfig = null;
			CommonParamsConfig.main();
		});
	}


	/**
	 * 打赏 listener
	 *
	 * @param giveMontyItem
	 */
	public void setGiveMoneyListener(JMenuItem giveMontyItem) {
		giveMontyItem.addActionListener(e -> {
			giveMoney();
		});
	}

	/**
	 * 下载 springcloud listener
	 *
	 * @param mntmSpringcloud
	 */
	public void setSpringCloudListener(JMenuItem mntmSpringcloud) {
		mntmSpringcloud.addActionListener(e -> {
			try {
				File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
				String desktopPath = desktopDir.getAbsolutePath() + (Constant.MAC_OS.equals(CodeWriterUtil.getSystemType()) ? "/Desktop/" : "/");
				UtilDownLoad.main(Constant.cloudModelZip, desktopPath, null);
				showDownLoadMsg();
			} catch (Exception ex) {
				JOptionPane.showMessageDialog(frmv, "拉取失败，请检查网络配置：" + ex.getMessage(), "提示", JOptionPane.INFORMATION_MESSAGE);
			}
		});
	}

	/**
	 * 下载 dubbo listener
	 *
	 * @param mntmDubbo
	 */
	public void setDubboListener(JMenuItem mntmDubbo) {
		mntmDubbo.addActionListener(e -> {
			try {
				File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
				String desktopPath = desktopDir.getAbsolutePath() + (Constant.MAC_OS.equals(CodeWriterUtil.getSystemType()) ? "/Desktop/" : "/");
				UtilDownLoad.main(Constant.dubboModelZip, desktopPath, null);
				showDownLoadMsg();
			} catch (Exception ex) {
				JOptionPane.showMessageDialog(frmv, "拉取失败，请检查网络配置：" + ex.getMessage(), "提示", JOptionPane.INFORMATION_MESSAGE);
			}
		});
	}

	/**
	 * 下载 everything listener
	 *
	 * @param mntmEverything
	 */
	public void setMenuEveryThingListener(JMenuItem mntmEverything) {
		mntmEverything.addActionListener(e -> SwingUtilities.invokeLater(() -> UtilDownLoad.main(Constant.everythingZip, Constant.EVERYTHING_DOWN_LOAD_DIR,
				Constant.EVERYTHING_EXE_NAME)));
	}

	/**
	 * 数据源配置的监听器
	 */
	public void setDataBaseSouceConfigListener() {
		dataSourceBtn.addActionListener(e -> {
			MutiTableConfig.main(new String[]{});
		});
	}

	/**
	 * 打赏一下监听器
	 */
	public void setMoneyBtnListener() {
		moneyBtn.addActionListener(e -> {
			giveMoney();
		});
	}


	/**
	 * 设置模块选择 listener
	 */
	public void setSelectModelBoxListener() {
		controllerBox.addActionListener(e -> {
			isAllBox.setSelected(false);
		});
		serviceBox.addActionListener(e -> {
			isAllBox.setSelected(false);
		});
		daoBox.addActionListener(e -> {
			isAllBox.setSelected(false);
		});
		entityBox.addActionListener(e -> {
			isAllBox.setSelected(false);
		});
		viewBox.addActionListener(e -> {
			isAllBox.setSelected(false);
		});
		isAllBox.addActionListener(e -> {
			controllerBox.setSelected(false);
			serviceBox.setSelected(false);
			daoBox.setSelected(false);
			entityBox.setSelected(false);
			viewBox.setSelected(false);
		});
	}

	/**
	 * 数据源下拉框监听
	 */
	public void setDataSourceBoxListener() {
		dataSouceBox.addItemListener(e -> {
			if (e.getStateChange() != ItemEvent.SELECTED) {
				return;
			}
			String dataSoucrce = (String) dataSouceBox.getSelectedItem();
			if (CodeConstant.PLEASE_CHOOSE.equals(dataSoucrce)) {
				databaseType.setSelectedItem("");
				dataBaseIp.setText("");
				dataBasePort.setText("");
				dataBasePwd.setText("");
				dataBaseName.setText("");
				dataBaseUserName.setText("");
				tableName.setText("");
				return;
			}
			DataSourceModel dataSourceModel = ChildWindowConstant.dataSourceModelMap.get(dataSoucrce);
			databaseType.setSelectedItem(dataSourceModel.getDataBaseTypeVal());
			dataBaseIp.setText(dataSourceModel.getDataBaseIpVal());
			dataBasePort.setText(dataSourceModel.getDataBasePortVal());
			dataBasePwd.setText(dataSourceModel.getDataBasePwdVal());
			dataBaseName.setText(dataSourceModel.getDataBaseNameVal());
			dataBaseUserName.setText(dataSourceModel.getDataBaseUserNameVal());
			tableName.setText(dataSourceModel.getTableName());
			//替换全局变量
			setStaticAttr(dataSourceModel);
		});
	}

	/**
	 * 数据源模式box listener
	 */
	public void setMutiDataSoucreBoxListener() {
		isMutiDataSource.addActionListener(e -> {
			if (isMutiDataSource.isSelected()) {
				JOptionPane.showMessageDialog(frmv, "选择多数据源模式生成的代码可以动态切换当前配置的所有数据源，生成后可以在 config 包下的 mutidatasource 包查看核心代码！", "提示", JOptionPane.INFORMATION_MESSAGE);
			}
		});
	}


	/**
	 * 检查数据项配置
	 *
	 * @return
	 */
	private boolean isNotPassDataBaseConfig(Parameters parameters, Map<String, List<String>> primaryKeyListMap, Map<String, List<DatabaseModel>> allColumnMsgMap, Map<String, List<DatabaseModel>> columnMsgMap) {
		Connection connection = DBUtils.getConnection(parameters);
		String dataSourceName = parameters.getDataSourceName();
		// 获取数据库连接，设置url和driverClass参数和connection
		String tableName = parameters.getTableName();
		if (!"".equals(tableName) && connection == null) {
			JOptionPane.showMessageDialog(frmv, "数据源 " + dataSourceName + " 的数据库连接有误，无法查询您配置的表，如果一定要生成，请先清空数据表的输入框再生成！", "警告", JOptionPane.ERROR_MESSAGE);
			return true;
		}
		if (connection == null) {
			JOptionPane.showMessageDialog(frmv, "数据源 " + dataSourceName + " 的数据库连接有误，生成后程序可能无法正常运行！", "警告", JOptionPane.ERROR_MESSAGE);
		}
		String[] tableNameArr = new String[]{};
		if (!"".equals(tableName)) {
			tableNameArr = tableName.split("#");
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException ignored) {
			}
		}
		// 检查是否每个表都进行了主键以及数据项的配置
		StringBuilder tipStr = new StringBuilder();
		// 检查每个表是否可以正常连接数据库查询
		for (int i = 0; i < tableNameArr.length; i++) {
			List<String> columnNameList = DBUtils.getColumnNameList(parameters.getDataBaseTypeVal(), tableNameArr[i],
					DBUtils.getConnection(parameters));
			if (columnNameList != null) {
				continue;
			}
			if (i == tableNameArr.length - 1) {
				tipStr.append(tableNameArr[i]);
				break;
			}
			tipStr.append(tableNameArr[i]).append(",");
		}
		// 如果提示不为空，说明有表名填写出现问题
		if (!"".equals(tipStr.toString())) {
			JOptionPane.showMessageDialog(frmv,
					"查询数据源 " + dataSourceName + " 的数据表 " + tipStr
							+ " 时出现未知错误！请仔细检查数据库相关信息（表名注意大小写）是否配置正确（postgresql需要模式名.表名（除public模式））！表名与表名之间是否使用#隔开！",
					"错误", JOptionPane.ERROR_MESSAGE);
			return true;
		}
		tipStr = new StringBuilder();
		for (int i = 0; i < tableNameArr.length; i++) {
			if (primaryKeyListMap.get(tableNameArr[i]) != null && !primaryKeyListMap.get(tableNameArr[i]).isEmpty()) {
				continue;
			}
			if (i == tableNameArr.length - 1) {
				tipStr.append(tableNameArr[i]);
				break;
			}
			tipStr.append(tableNameArr[i]).append(",");
		}
		// 如果提示不为空 证明有表没有配置主键
		if (!"".equals(tipStr.toString())) {
			JOptionPane.showMessageDialog(frmv, "检测到数据源 " + dataSourceName + " 的 " + tipStr + " 数据表没有配置主键，请在数据项配置中进行配置！", "提示",
					JOptionPane.INFORMATION_MESSAGE);
			// 自动打开数据库配置界面
			if (ChildWindowConstant.dataBaseConfig == null) {
				DataBaseConfig.main(parameters);
			} else {
				ChildWindowConstant.dataBaseConfig.dispose();
				ChildWindowConstant.dataBaseConfig = null;
				DataBaseConfig.main(parameters);
			}
			return true;
		}
		// 配完主键后
		tipStr = new StringBuilder();
		for (int i = 0; i < tableNameArr.length; i++) {
			if (allColumnMsgMap.get(tableNameArr[i]) != null) {
				continue;
			}
			if (i == tableNameArr.length - 1) {
				tipStr.append(tableNameArr[i]);
				break;
			}
			tipStr.append(tableNameArr[i]).append(",");
		}
		// 如果不为空 说明有表的字段信息没有进行配置
		if (!"".equals(tipStr.toString())) {
			JOptionPane.showMessageDialog(frmv,
					"检测到数据源 " + dataSourceName + " 没有进行表 " + tipStr + " 的字段配置，请在数据库配置中点击 确定 进行配置!", "提示", JOptionPane.INFORMATION_MESSAGE);
			if (ChildWindowConstant.dataBaseConfig == null) {
				DataBaseConfig.main(parameters);
			} else {
				ChildWindowConstant.dataBaseConfig.dispose();
				ChildWindowConstant.dataBaseConfig = null;
				DataBaseConfig.main(parameters);
			}
			return true;
		}
		//配置完表信息后
		tipStr = new StringBuilder();
		for (int i = 0; i < tableNameArr.length; i++) {
			if (columnMsgMap.get(tableNameArr[i]).size() != 0) {
				continue;
			}
			if (i == tableNameArr.length - 1) {
				tipStr.append(tableNameArr[i]);
				break;
			}
			tipStr.append(tableNameArr[i]).append(",");
		}
		// 如果不为空 说明有表的字段信息没有进行配置
		if (!"".equals(tipStr.toString())) {
			int ifGo = JOptionPane.showConfirmDialog(frmv,
					"检测到数据源 " + dataSourceName + " 没有进行表 " + tipStr + " 的数据项配置，将默认查询并展示表的所有的字段项目" + CodeConstant.NEW_LINE
							+ "是否前去配置？",
					"提示", JOptionPane.YES_NO_OPTION);
			if (ifGo == 0) {
				if (ChildWindowConstant.dataBaseConfig == null) {
					DataBaseConfig.main(parameters);
				} else {
					ChildWindowConstant.dataBaseConfig.dispose();
					ChildWindowConstant.dataBaseConfig = null;
					DataBaseConfig.main(parameters);
				}
				return true;
			}
		}
		return false;
	}

	/**
	 * 打赏
	 */
	private void giveMoney() {
		if (ChildWindowConstant.callGood == null) {
			CallGood.main(new String[]{});
			return;
		}
		ChildWindowConstant.callGood.dispose();
		ChildWindowConstant.callGood = null;
		CallGood.main(new String[]{});
	}

	/**
	 * 生成动态用户的方法
	 *
	 * @param loginItem
	 * @return
	 */
	private boolean dealDymaicAndStaticUser(String loginItem) {
		if ("静态用户".equals(loginItem)) {
			if (ChildWindowConstant.user1.size() == 0 && ChildWindowConstant.user2.size() == 0
					&& ChildWindowConstant.user3.size() == 0) {
				ChildWindowConstant.user1.add("admin");
				ChildWindowConstant.user1.add("root");
			}
		} else if ("动态用户".equals(loginItem)) {
			if (ChildWindowConstant.dynamicUserList.size() == 0) {
				JOptionPane.showMessageDialog(frmv, "检测到你没有进行动态用户的配置，请先配置！", "提示", JOptionPane.INFORMATION_MESSAGE);
				if (ChildWindowConstant.loginConfig == null) {
					LoginConfig.main();
					return false;
				}
				ChildWindowConstant.loginConfig.getFrame().dispose();
				ChildWindowConstant.loginConfig = null;
				LoginConfig.main();
				return false;
			}
		}
		return true;
	}

	/**
	 * 检查必填项目
	 *
	 * @return
	 */
	private Parameters checkNeccessary() {
		String dataBaseIpVal = dataBaseIp.getText();
		String dataBasePortVal = dataBasePort.getText();
		String dataBasePwdVal = dataBasePwd.getText();
		String dataBaseNameVal = dataBaseName.getText();
		String dataBaseUserNameVal = dataBaseUserName.getText();
		String tableNameVal = tableName.getText();
		String outPathVal = outPath.getText();
		if ("".equals(dataBaseIpVal) || "".equals(dataBasePortVal) || "".equals(dataBasePwdVal)
				|| "".equals(dataBaseNameVal) || "".equals(dataBaseUserNameVal) || "".equals(outPathVal)) {
			return null;
		}
		Parameters parameters = new Parameters();
		parameters.setDataBaseTypeVal((String) databaseType.getSelectedItem());
		parameters.setDataBaseIpVal(dataBaseIpVal);
		parameters.setDataBasePortVal(dataBasePortVal);
		parameters.setDataBasePwdVal(dataBasePwdVal);
		parameters.setDataBaseNameVal(dataBaseNameVal);
		parameters.setDataBaseUserNameVal(dataBaseUserNameVal);
		parameters.setTableName(tableNameVal);
		parameters.setOutPathVal(outPathVal);
		//设置数据源相关参数
		String dataSource = (String) dataSouceBox.getSelectedItem();
		parameters.setDataSourceName(dataSource);
		parameters.setMutiDataSource(isMutiDataSource.isSelected());
		//设置当前数据源全局变量
		DataSourceModel dataSourceModel = ChildWindowConstant.dataSourceModelMap.get(dataSource);
		//设置全局静态变量
		setStaticAttr(dataSourceModel);
		return parameters;
	}

	private void setStaticAttr(DataSourceModel dataSourceModel) {
		//单表
		ChildWindowConstant.columnMsgMap = dataSourceModel.getColumnMsgMap();
		ChildWindowConstant.queryColumnMsgMap = dataSourceModel.getQueryColumnMsgMap();
		ChildWindowConstant.updateColumnMsgMap = dataSourceModel.getUpdateColumnMsgMap();
		ChildWindowConstant.allColumnMsgMap = dataSourceModel.getAllColumnMsgMap();
		ChildWindowConstant.currentTableCnNameMap = dataSourceModel.getCurrentTableCnNameMap();
		ChildWindowConstant.primaryKeyListMap = dataSourceModel.getPrimaryKeyListMap();
		ChildWindowConstant.currentTableNameAndTypes = dataSourceModel.getCurrentTableNameAndTypes();
		//多表
		ChildWindowConstant.tablesQueryMap = dataSourceModel.getTablesQueryMap();
		ChildWindowConstant.tablesQueryEndAndCnMap = dataSourceModel.getTablesQueryEndAndCnMap();
	}

	/**
	 * 显示下载信息
	 */
	private void showDownLoadMsg() {
		while (true) {
			if (UtilDownLoad.downFlag) {
				JOptionPane.showMessageDialog(frmv, "拉取成功！已下载到桌面", "提示", JOptionPane.INFORMATION_MESSAGE);
				UtilDownLoad.downFlag = false;
				break;
			}
		}
	}

}
